<?php
class tools
{
    /**
     *方便的调试方法

     * @author 王鹏
     * @access public
     * @param mixed $mix_var  要输出的值
     * @since 1.0
     */
    public function xbug($mix_var,$die = false,$name = '')
    {
        if(is_string($die))
        {
            $name = $die;
            $die = false;
        }
        if(!empty($name))
        {
            $name = "[$name]";
        }
        echo "<div style='border:solid 2px #FF6600;background-color:#FFFEFC;padding:1em 0.5em;'><strong style='color:red;font-weight:bold;'>$name</strong><pre style='margin-left:1em;color:#243F61;'>",var_dump($mix_var),"</pre></div>";
        if($die)
        {
            die();
        }
    }
    /**
     *返回值方法

     * @author 黄宇翔
     * @access public
     * @param mixed $code  错误代码
     * @param mixed $promptInfo  返回的提示信息
     * @param $data 数据信息，默认为null
     * @since 1.0
     * @return Boolean
     */
    public function prompt($code,$promptInfo,$data=null){
        return array(
            'code' => $code,
            'msg'  => $promptInfo,
            'data' => $data ? $data : array()
        );
    }
    /**
     *检查字符串长度是否符合要求

     * @author 王鹏
     * @access public
     * @param mixed $theelement  字符串
     * @param mixed $min  最小长度
     * @param $data $max，最大长度
     * @since 1.0
     * @return Boolean
     */
    public function isStrLength($val, $min, $max)
    {
        $strlen = mb_strlen(trim($val), 'utf8');
        if($strlen < $min || $strlen > $max){
            return FALSE;
        }
        return TRUE;
    }
    /**
     *检查输入是否为英文

     * @author 王鹏
     * @access public
     * @param mixed $theelement  字符串
     * @since 1.0
     * @return Boolean
     */
    public function isEnglish($theelement)
    {
        if( preg_match("[\x80-\xff].",$theelement) )
        {
            Return false;
        }
        Return true;
    }

    /**
     *检查输入是否为中文

     * @author 王鹏
     * @access public
     * @param mixed $theelement  字符串
     * @since 1.0
     * @return Boolean
     */
    public function isChinese($sInBuf)
    {
        if (preg_match("/^[\x7f-\xff]+$/", $sInBuf)) { //兼容gb2312,utf-8

            return true;
        }
        else
        {
            return false;
        }
    }
    /**
     *验证手机号

     * @author 王鹏
     * @access public
     * @param mixed $mobile  手机号
     * @since 1.0
     * @return Boolean
     */
    public function valid_mobile($mobile){
        if(strlen($mobile)!=11) return false;
        if(preg_match('/13[0-9]\d{8}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8}/',$mobile)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取客户端真实IP

     * @author 王鹏
     * @access public
     * @since 1.0
     * @return IP
     */
    public function get_client_ip(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }

    /**
     * 检查数据是否是99999.99格式

     * @author 王鹏
     * @access public
     * @param mixed $money  待检测的数字
     * @since 1.0
     * @return Boolean
     */
    public function check_num($num) {
        if($num > 0){
            if(strpos($num,'.') === FALSE){
                $int = intval($num);
                if($int == $num){
                    return TRUE;
                }
            }
            else{
                if($num >= 1){
                    if(preg_match("/^[1-9][\d]*\.[\d]{0,2}$/", $num)) {
                        return TRUE;
                    }
                }
                else if(preg_match("/^0\.[\d]{0,2}$/", $num)) {
                    return TRUE;
                }
            }
        }
        return FALSE;
    }
    /**
     * 二维数组 取指定字段 的值集合

     * @author 王鹏
     * @access public
     * @since 1.0
     * @return 字符串
     */
    public function get_array_fields($list = array(), $fields = '') {
        if (is_array($list) && $fields) {
            if (is_string($fields)) {
                $fields = explode(',', str_replace(' ', '', $fields));
            }
            $fields = array_filter(array_unique($fields), function($val){
                if ($val === '' || $val === null) {
                    return false;
                } else {
                    return true;
                }
            });
            $data = array();
            foreach ($list as $value) {
                foreach ($fields as $field) {
                    if (isset($value[$field])) {
                        $data[] = $value[$field];
                    }
                }
            }
            $data = array_unique($data);
            return $data;
        } else {
            return false;
        }
    }
    /**
     * 对查询结果集进行排序
     *
     * @access public
     * @param array $list 查询结果
     * @param string $field 排序的字段名
     * @param array $sortby 排序类型
     * asc正向排序 desc逆向排序 nat自然排序
     * @return array
     */
    public function list_sort_by($list,$field, $sortby='asc') {
        if(is_array($list)){
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
                $refer[$i] = &$data[$field];
            switch ($sortby) {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc':// 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ( $refer as $key=> $val)
                $resultSet[] = &$list[$key];
            return $resultSet;
        }
        return false;
    }
    /**
     * 将数组按照指定 键值生成 主从组合

     * @author 王鹏
     * @access public
     * @since 1.0
     * @return 字符串
     */
    public function list_to_tree($list, $parent_key='id', $parent_id = 'pid', $child_str = '_child', $top_level = 0) {
        $top_level_r = array();
        if(is_array($list)) {
            // 创建基于主键的数组引用
            foreach ($list as $key => $val) {
                $parentId = $val[$parent_id];
                if ($top_level == $parentId) {
                    $top_level_r[$val[$parent_key]] = $list[$key];
                }
            }
            foreach ($list as $key => $val) {
                // 判断是否存在parent
                if ($top_level != $val[$parent_id] && isset($top_level_r[$val[$parent_id]])) {
                    $top_level_r[$val[$parent_id]][$child_str][] = $list[$key];
                }
            }
        }
        return array_values($top_level_r);
    }

    /**
     * 生成一个随机的sha1 值

     * @author 王鹏
     * @access public
     * @since 1.0
     * @return 字符串
     */
    public function random_sha1() {
        static $secret_key = '';
        if ($secret_key === '') {
            $secret_key = 'aosdknwaerxzcoi';
        }
        $remote_addr  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        $remote_port  = isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : '';
        $user_agent   = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $current_time = microtime(true);
        $random_num   = mt_rand();
        $uniqid       = uniqid($secret_key, true);
        return sha1($secret_key . $remote_addr . $remote_port . $user_agent . $current_time . $random_num . $uniqid);
    }

    /**
     * 加x补位置

     * @author 王鹏
     * @access public
     * @param mixed $str  待添加字符串
     * @param mixed $len  长度
     * @param mixed $msg  添加的字符串
     * @param mixed $type  1 往后添加  0往前补位
     * @since 1.0
     * @return 字符串
     */
    public function dispRepair($str, $len, $msg, $type='1') {
        $length = $len - strlen($str);
        if($length<1)return $str;
        if ($type == 1) {
            $str = str_repeat($msg,$length).$str;
        } else {
            $str .= str_repeat($msg,$length);
        }
        return $str;
    }
    /**
     * 加x补位置

     * @author 王鹏
     * @access public
     * @param mixed $num  待验证字符串
     * @since 1.0
     * @return Boolean
     */
    public function is_positive($num) {
        if(is_numeric($num)){
            if($num > 0){
                $int_num = intval($num);
                if($int_num == $num){
                    return TRUE;
                }
            }
        }
        return FALSE;
    }

    public function resolve_url($url)
    {
        $data = array();
        if (strpos($url,'?'))
        {
            $parameter = @ explode('&',next(explode('?',$url)));
            foreach($parameter as $val){
                $tmp = explode('=',$val);
                if (!isset($data[$tmp[0]]) && count($tmp) == 2)
                {
                    $data[$tmp[0]] = $tmp[1];
                }
            }
        }
        return $data;
    }
    /**
     * 生成随机字符串

     * @author 王鹏
     * @access public
     * @param mixed $num  生成数量
     * @param mixed $length  字符串长度
     * @since 1.0
     * @return Boolean
     */
    public function generate_str($num,$length = 10,$data = array())
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $rand_arr = array();
        for($j=0;$j<$num;$j++){
            $rand_string = '';
            for ($i = 0; $i < $length; $i++) {
                $rand_string .= $chars[mt_rand(0, strlen($chars) - 1)];
            }
            $rand_arr[] = $rand_string;
        }
        if(count(array_unique($rand_arr)) < $num){
            $rand_arr = array_merge($data, $rand_arr);
            $this->generate_str($num - count(array_unique($rand_arr)), 10, $rand_arr);
        }
        return array_merge($data, $rand_arr);
    }
    /**
     * 生成按日期的字符串

     * @author 王鹏
     * @access public
     * @param mixed $id  唯一性标识
     * @since 1.0
     * @return Boolean
     */
    public function generateuuid_no($id){
        $str=substr(sha1($id),8,8);
        return date('ymdHis').$str.substr(microtime(),2,5);
    }
    //
    public function draw_win_id($draw_prizes, $max=10000){
        $draw_number = rand(1, $max);
        $draw_prizes_section = array();
        $next = 0;

        foreach($draw_prizes as $id => $probability){
            $next += $probability*100;
            $draw_prizes_section[$next] = $id;
        }
        foreach($draw_prizes_section as $number => $id )
        {
            if($draw_number <= $number){
                return $id;
            }
        }
        return 0;
    }
    //
    public function generate_code($type) {
        if($type == 'MOBILE'){
            $code = rand(pow(10,(4-1)), pow(10,4)-1);
        }
        else {
            $code = $this->random_sha1();
        }
        return $code;
    }
    //生成随机字符串的方法
    public function generateNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    //验证邮箱
    public function valid_email($address)
    {
        return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
    }
}
?>